<template>
  <div>
    <!-- 使用isAdd 展示添加还是编辑 -->
    <el-dialog
      :title="info.isAdd?'商品添加':'商品编辑'"
      :visible.sync="info.isshow"
      @closed="closed"
      @close="close"
      @opened="opened"
    >
      {{form}}
      <el-form :model="form">
        <!-- 2.绑定数据 -->
        <el-form-item label="一级分类" label-width="120px">
          <el-select placeholder="请选择" v-model="form.first_cateid" @change="changeFirstCateId">
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类" label-width="120px">
          <el-select placeholder="请选择" v-model="form.second_cateid">
            <el-option
              v-for="item in secondCateList"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" label-width="120px">
          <el-input v-model="form.goodsname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="价格" label-width="120px">
          <el-input v-model="form.price" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="图片" label-width="120px">
          <!-- 3.图片 -->
          <!-- 我的上传文件 -->
          <!-- <div class="my-upload">
            <h3 class="my-plus">+</h3>
            <img v-if="imgUrl" class="my-img" :src="imgUrl" alt />
            <input type="file" @change="changeFile" />
          </div>-->

          <!-- element-ui上传文件 -->
          <my-upload @sendFile="sendFile" ref="upload"></my-upload>
        </el-form-item>
        <el-form-item label="商品规格" label-width="120px">
          <el-select placeholder="请选择" v-model="form.specsid" @change="changeSpecsId">
            <el-option
              v-for="item in specsList"
              :key="item.id"
              :label="item.specsname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格属性" label-width="120px">
          <el-select placeholder="请选择" multiple v-model="form.specsattr">
            <el-option v-for="item in attrsArr" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否新品" label-width="120px">
          <template>
            <el-switch v-model="form.isnew" :active-value="1" :inactive-value="2"></el-switch>
          </template>
        </el-form-item>
        <el-form-item label="是否热卖" label-width="120px">
          <template>
            <el-switch v-model="form.ishot" :active-value="1" :inactive-value="2"></el-switch>
          </template>
        </el-form-item>
        <el-form-item label="状态" label-width="120px">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="2"></el-switch>
        </el-form-item>
        <el-form-item label="商品描述" label-width="120px">
          <!-- 二、富文本编辑器  添加了条件渲染-->
          <div id="editor" v-if="info.isshow"></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" v-if="info.isAdd" @click="add">添 加</el-button>
        <el-button type="primary" v-else @click="update">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import E from "wangeditor";
import {
  reqcatelist,
  reqgoodsedit,
  reqcateinfo,
  reqgoodsadd,
  reqroleinfo,
  reqgoodsinfo,
} from "../../../request/api";
import { errorAlert, successAlert } from "../../../utils/alert";
import path from "path";
import { mapGetters, mapActions } from "vuex";
export default {
  components: {},
  props: ["info"],
  data() {
    return {
      // 1.初始化数据
      form: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        img: null,
        description: "",
        specsid: "",
        specsattr: [],
        isnew: 2,
        ishot: 2,
        status: 2,
      },

      //二级分类的列表
      secondCateList: [],
      //规格属性的列表
      attrsArr: [],
    };
  },
  computed: {
    ...mapGetters({
      cateList: "cate/list", //分类列表
      specsList: "specs/list", //规格列表
    }),
  },
  mounted() {
    //3.请分类列表
    if (this.cateList.length == 0) {
      this.reqcateList();
    }
    // 8.请求规格列表
    this.reqSpecsList(true);
  },
  methods: {
    ...mapActions({
      reqcateList: "cate/reqList", //请求分类列表
      reqSpecsList: "specs/reqList", //请求分类列表
      reqList: "goods/reqList",
      reqCount: "goods/reqCount",
    }),

    //一、创建编辑器
    opened() {
      //创建一个编辑器
      this.editor = new E("#editor");
      this.editor.create();
      //给编辑器赋值
      this.editor.txt.html(this.form.description);
    },
    // 关闭弹框
    close() {
      this.form.description = this.editor.txt.html();
    },
    // 5.修改了1级分类id
    changeFirstCateId() {
      //清空二级的数据
      this.form.second_cateid = "";

      //获取二级列表
      this.getSecondCateList();
    },
    getSecondCateList() {
      //根据1级 的id取二级分类的列表
      reqcatelist({
        pid: this.form.first_cateid,
      }).then((res) => {
        if (res.data.code == 200) {
          this.secondCateList = res.data.list ? res.data.list : [];
        }
      });
    },

    //9.修改了规格，计算规格属性
    changeSpecsId() {
      //清空规格属性的数据
      this.form.specsattr = [];
      this.getAttrsArr();
    },
    //计算规格属性列表
    getAttrsArr() {
      // 将specsList 中id和form.specsid 一致的数据的attrs赋值给 attrsArr
      let obj = this.specsList.find((item) => item.id == this.form.specsid);
      this.attrsArr = obj ? obj.attrs : []; //["s","m","l"]
    },

    // /7.接收子组件传的文件
    sendFile(file) {
      this.form.img = file;
    },

    //取消
    cancel() {
      this.info.isshow = false;
    },
    //弹框关闭
    closed() {
      if (!this.info.isAdd) {
        this.empty();
      }
    },
    //重置form
    empty() {
      this.form = {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: null,
        description: "",
        specsid: "",
        specsattr: [],
        isnew: 2,
        ishot: 2,
        status: 2,
      };
      //二级分类的列表
      this.secondCateList = [];
      //规格属性的列表
      this.attrsArr = [];
      //清空图片的imgUrl
      this.$refs.upload.imgUrl = "";
    },
    //验空的函数
    checkEmpty() {
      return new Promise((resolve, reject) => {
        if (this.form.first_cateid == "") {
          errorAlert("一级分类不能为空");
          return;
        }
        if (this.form.second_cateid == "") {
          errorAlert("二级分类不能为空");
          return;
        }
        if (this.form.goodsname == "") {
          errorAlert("商品名称不能为空");
          return;
        }
        if (this.form.price == "") {
          errorAlert("价格不能为空");
          return;
        }
        // if (this.form.market_price == "") {
        //   errorAlert("市场价格不能为空");
        //   return;
        // }
        if (!this.form.img) {
          errorAlert("图片不能为空");
          return;
        }
        if (this.form.specsid == "") {
          errorAlert("规格不能为空");
          return;
        }
        if (this.form.specsattr.length == 0) {
          errorAlert("规格属性不能为空");
          return;
        }
        if (this.editor.txt.html() === "") {
          errorAlert("描述不能空");
          return;
        }
        resolve();
      });
    },
    //添加
    add() {
      //验空
      this.checkEmpty().then(() => {
        // 数据交互
        reqgoodsadd({
          ...this.form,
          specsattr: this.form.specsattr.join(","),
          //将编辑器内容给description
          description: this.editor.txt.html(),
        }).then((res) => {
          if (res.data.code == 200) {
            //成功了
            // （1）弹成功
            successAlert(res.data.msg);
            // (2)弹框消失
            this.cancel();
            // (3)清空数据
            this.empty();
            // (4)刷新列表
            this.reqList(), this.reqCount();
          }
        });
      });
    },
    //修改了上级菜单
    changePid() {
      // 如果上级菜单是顶级菜单，就是目录；否则就是菜单
      if (this.form.pid == 0) {
        this.form.type = 1;
      } else {
        this.form.type = 2;
      }
    },
    //获取一条数据
    getOne(id) {
      reqgoodsinfo({ id: id }).then((res) => {
        if (res.data.code == 200) {
          this.form = res.data.list;
          //（1）补id
          this.form.id = id;
          // (2)获取二级列表
          this.getSecondCateList();
          // (3)修改图片地址
          this.$refs.upload.imgUrl = this.$pre + this.form.img;
          //(4).修改规格属性
          this.form.specsattr = this.form.specsattr.split(",");
          // (5)计算属性列表
          this.getAttrsArr();
          // (6)给富文本编辑器赋值 动画2s 请求1s[4s]
          if (!!this.editor) {
            this.editor.txt.html(this.form.description);
          }
        }
      });
    },
    //修改
    update() {
      this.checkEmpty().then(() => {
        reqgoodsedit({
          ...this.form,
          specsattr: this.form.specsattr.join(","),
          description: this.editor.txt.html(),
        }).then((res) => {
          if (res.data.code == 200) {
            // （1）弹成功
            successAlert(res.data.msg);
            // (2)弹框消失
            this.cancel();
            // (3)清空数据
            this.empty();
            // (4)刷新列表
            this.reqList();
          }
        });
      });
    },
  },
};
</script>
<style lang="less" scoped>
@import "../../../less/index.less";
.my-upload {
  width: 100px;
  height: 100px;
  border: 1px dashed @header-color;
  position: relative;
}
.my-plus {
  width: 100%;
  height: 100%;
  text-align: center;
  line-height: 100px;
  color: @primary;
}
.my-img {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
}
.my-upload input {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
}

// /deep/.avatar-uploader .el-upload {
//     border: 1px dashed #d9d9d9;
//     border-radius: 6px;
//     cursor: pointer;
//     position: relative;
//     overflow: hidden;
//   }
//   .avatar-uploader .el-upload:hover {
//     border-color: #dddddd;
//   }
//   .avatar-uploader-icon {
//     font-size: 28px;
//     color: #8c939d;
//     width: 178px;
//     height: 178px;
//     line-height: 178px;
//     text-align: center;
//   }
//   .avatar {
//     width: 178px;
//     height: 178px;
//     display: block;
//   }
</style>